package com.wlyuan.open.scanner.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlyuan.open.scanner.dao.entity.CompanyDO;
import com.wlyuan.open.scanner.dao.entity.PostPoneCodeDO;
import com.wlyuan.open.scanner.dao.mapper.PostPoneCodeMapper;
import com.wlyuan.open.scanner.domain.tenant.TenantConfig;
import com.wlyuan.open.scanner.repository.PostPoneCodeRepository;
import com.wlyuan.open.scanner.utils.StreamUtils;
import com.wlyuan.open.scanner.utils.enums.TenantConfigTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PostPoneCodeRepositoryImpl implements PostPoneCodeRepository {
    private final PostPoneCodeMapper postPoneCodeMapper;

    @Override
    public void tenantConfig(CompanyDO company) {
        var map = getPoneCodeMap(company.getCompanyId());
        if (!CollectionUtils.isEmpty(map)) {
            TenantConfig config = new TenantConfig();
            var deliver = map.get(TenantConfigTypeEnum.DELIVER.getValue());
            Optional.ofNullable(deliver).ifPresent(d -> {
                config.setDeliveryTime(Arrays.asList(d.getPostponeSat(), d.getPostponeSun(), d.getPostponeHolidays(), d.getPostponeRestday()).stream().filter(Objects::nonNull).collect(Collectors.toList()));
            });
            var receipt = map.get(TenantConfigTypeEnum.RECEIPT.getValue());
            Optional.ofNullable(receipt).ifPresent(r -> {
                config.setReceiptTime(Arrays.asList(r.getPostponeSat(), r.getPostponeSun(), r.getPostponeHolidays(), r.getPostponeRestday()).stream().filter(Objects::nonNull).collect(Collectors.toList()));
            });
            company.setTenantConfig(config);
        }
    }

    private Map<Integer, PostPoneCodeDO> getPoneCodeMap(Long companyId) {
        LambdaQueryWrapper<PostPoneCodeDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PostPoneCodeDO::getUsercompanyId, companyId).eq(PostPoneCodeDO::getPostponeStatus, 1)
                .isNotNull(PostPoneCodeDO::getPostponeType);
        var list = postPoneCodeMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        return StreamUtils.maxByGroup(list, PostPoneCodeDO::getPostponeType, Comparator.comparing(PostPoneCodeDO::getPostponeTime));
    }

}
